<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h3>注册成功</h3>
    <form action="http://localhost:3000/register" method="POST">
      邮箱:<input type="text" name="email" /><span></span><br />
      用户名:<input type="text" name="username" /><span></span><br />
      密码:<input type="password" name="psd" autocomplete="off" /><span></span
      ><br />
      <input type="submit" value="注册" />
    </form>
    <script>
      const emailReg = /^\w{1,10}@\w{1,20}\.(com|cn)$/;
      const userReg = /^[a-zA-Z0-9_-]{4,16}$/;
      const psdReg = /^[a-zA-Z]\w{5,17}$/;
      const email = document.querySelector("input[name=email]");
      const username = document.querySelector("input[name=username]");
      const psd = document.querySelector("input[name=psd]");
      const submit = document.querySelector("input[type=submit]");
      let emailFlag = { flag: false };
      let usernameFlag = { flag: false };
      let psdFlag = { flag: false };
      function tip(element, message, color) {
        const span = element.nextElementSibling;
        span.textContent = message;
        span.style.color = color;
        return;
      }
      function validator(messageTips, successTips, typeReg, selectFlag) {
        const typeVal = this.value;
        if (!typeVal) {
          tip(this, messageTips, "red");
          selectFlag.flag = false;
        }

        if (typeReg.test(typeVal)) {
          tip(this, successTips, "green");
          selectFlag.flag = true;
        } else {
          tip(this, messageTips, "red");
          selectFlag.flag = false;
        }
      }

      email.addEventListener("blur", function () {
        validator.call(
          this,
          "请输入正确的邮箱格式",
          "验证成功",
          emailReg,
          emailFlag
        );
      });
      email.addEventListener("focus", () => {
        tip(email, "", "");
      });

      username.addEventListener("blur", function () {
        validator.call(
          this,
          "请输入4到16位（字母，数字，下划线，减号）",
          "",
          userReg,
          usernameFlag
        );
      });
      username.addEventListener("focus", () => {
        tip(username, "", "");
      });

      psd.addEventListener("blur", function () {
        validator.call(
          this,
          "以字母开头，长度在6~18之间，只能包含字母、数字和下划线",
          "",
          psdReg,
          psdFlag
        );
      });
      psd.addEventListener("focus", () => {
        tip(psd, "", "");
      });

      submit.onclick = function (e) {
        if (!(emailFlag.flag && usernameFlag.flag && psdFlag.flag)) {
          e.preventDefault();
          alert('请输入正确的邮箱/用户名/密码')
          return;
        }
      };
    </script>
  </body>
</html>
